import React, { useState } from 'react';
import type { Employee } from '../types';
import EmployeeModal from './EmployeeModal';
import * as api from '../services/api';
import { PlusIcon } from './icons/PlusIcon';
import { EditIcon } from './icons/EditIcon';
import { DeleteIcon } from './icons/DeleteIcon';

interface EmployeeListProps {
  employees: Employee[];
  onDataChange: () => void;
}

const EmployeeList: React.FC<EmployeeListProps> = ({ employees, onDataChange }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedEmployee, setSelectedEmployee] = useState<Employee | null>(null);

  const handleAddEmployee = () => {
    setSelectedEmployee(null);
    setIsModalOpen(true);
  };

  const handleEditEmployee = (employee: Employee) => {
    setSelectedEmployee(employee);
    setIsModalOpen(true);
  };

  const handleDeleteEmployee = async (id: number) => {
    if (window.confirm('您确定要删除该员工吗？')) {
      try {
        await api.deleteEmployee(id);
        onDataChange();
      } catch (error) {
        console.error("Failed to delete employee:", error);
        alert("删除失败，请重试。");
      }
    }
  };

  const handleSaveEmployee = async (employee: Omit<Employee, 'id' | 'avatar'> & { id?: number }) => {
    try {
      if (employee.id) {
        await api.updateEmployee(employee.id, employee);
      } else {
        await api.addEmployee(employee);
      }
      onDataChange();
      setIsModalOpen(false);
    } catch (error) {
      console.error("Failed to save employee:", error);
      alert("保存失败，请重试。");
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-3xl font-bold text-slate-800">员工管理</h2>
        <button onClick={handleAddEmployee} className="flex items-center bg-indigo-600 text-white px-4 py-2 rounded-lg shadow-md hover:bg-indigo-700 transition-colors">
          <PlusIcon />
          <span className="ml-2">添加员工</span>
        </button>
      </div>

      <div className="bg-white p-6 rounded-xl shadow-md">
        <div className="overflow-x-auto">
          <table className="w-full text-sm text-left text-slate-500">
            <thead className="text-xs text-slate-700 uppercase bg-slate-50">
              <tr>
                <th scope="col" className="px-6 py-3">姓名</th>
                <th scope="col" className="px-6 py-3">职位</th>
                <th scope="col" className="px-6 py-3">部门</th>
                <th scope="col" className="px-6 py-3">入职日期</th>
                <th scope="col" className="px-6 py-3 text-right">操作</th>
              </tr>
            </thead>
            <tbody>
              {employees.map(employee => (
                <tr key={employee.id} className="bg-white border-b hover:bg-slate-50">
                  <th scope="row" className="px-6 py-4 font-medium text-slate-900 whitespace-nowrap flex items-center">
                    <img className="w-10 h-10 rounded-full" src={employee.avatar} alt={`${employee.name} avatar`} />
                    <div className="pl-3">
                        <div className="text-base font-semibold">{employee.name}</div>
                        <div className="font-normal text-slate-500">{employee.email}</div>
                    </div>
                  </th>
                  <td className="px-6 py-4">{employee.position}</td>
                  <td className="px-6 py-4">{employee.department}</td>
                  <td className="px-6 py-4">{employee.hireDate}</td>
                  <td className="px-6 py-4 text-right">
                    <div className="flex justify-end space-x-2">
                        <button onClick={() => handleEditEmployee(employee)} className="p-2 text-slate-500 hover:text-indigo-600 hover:bg-indigo-100 rounded-full transition-colors">
                            <EditIcon />
                        </button>
                        <button onClick={() => handleDeleteEmployee(employee.id)} className="p-2 text-slate-500 hover:text-red-600 hover:bg-red-100 rounded-full transition-colors">
                            <DeleteIcon />
                        </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      
      {isModalOpen && (
        <EmployeeModal
          employee={selectedEmployee}
          onClose={() => setIsModalOpen(false)}
          onSave={handleSaveEmployee}
        />
      )}
    </div>
  );
};

export default EmployeeList;